{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "import torch\n",
    "from torchvision.utils import make_grid\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from datasets import get_CIFAR10, get_SVHN, postprocess\n",
    "from model import Glow\n",
    "\n",
    "device = torch.device(\"cuda\")\n",
    "\n",
    "output_folder = 'output/'\n",
    "model_name = 'glow_model_250.pth'\n",
    "\n",
    "with open(output_folder + 'hparams.json') as json_file:  \n",
    "    hparams = json.load(json_file)\n",
    "    \n",
    "image_shape, num_classes, _, test_cifar = get_CIFAR10(hparams['augment'], hparams['dataroot'], hparams['download'])\n",
    "image_shape, num_classes, _, test_svhn = get_SVHN(hparams['augment'], hparams['dataroot'], hparams['download'])\n",
    "\n",
    "\n",
    "model = Glow(image_shape, hparams['hidden_channels'], hparams['K'], hparams['L'], hparams['actnorm_scale'],\n",
    "             hparams['flow_permutation'], hparams['flow_coupling'], hparams['LU_decomposed'], num_classes,\n",
    "             hparams['learn_top'], hparams['y_condition'])\n",
    "\n",
    "model.load_state_dict(torch.load(output_folder + model_name))\n",
    "model.set_actnorm_init()\n",
    "\n",
    "model = model.to(device)\n",
    "\n",
    "model = model.eval()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sample(model):\n",
    "    with torch.no_grad():\n",
    "        if hparams['y_condition']:\n",
    "            y = torch.eye(num_classes)\n",
    "            y = y.repeat(batch_size // num_classes + 1)\n",
    "            y = y[:32, :].to(device) # number hardcoded in model for now\n",
    "        else:\n",
    "            y = None\n",
    "\n",
    "        images = postprocess(model(y_onehot=y, temperature=1, reverse=True))\n",
    "\n",
    "    return images.cpu()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "images = sample(model)\n",
    "grid = make_grid(images[:30], nrow=6).permute(1,2,0)\n",
    "\n",
    "plt.figure(figsize=(10,10))\n",
    "plt.imshow(grid)\n",
    "plt.axis('off')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
